package com.commons.tools.utils;

import com.alibaba.excel.context.*;
import com.alibaba.excel.event.*;

import java.util.*;
import java.util.concurrent.*;

public class ExcelListenerUtils extends AnalysisEventListener<Map<Integer, String>> {

    //Excel数据
    private List<Map<Integer, Map<Integer, String>>> list;
    //Excel列名
    private Map<Integer, String> headTitleMap;

    public ExcelListenerUtils() {
        list = new CopyOnWriteArrayList<>();
        headTitleMap = new ConcurrentHashMap<>();
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        //System.out.println("解析到一条数据：" + JSON.toJSONString(data));
        Map<Integer, Map<Integer, String>> map = new HashMap<>();
        map.put(context.readRowHolder().getRowIndex(), data);
        list.add(map);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //System.out.println("所有数据解析完成");
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        headTitleMap = headMap;
    }

    public List<Map<Integer, Map<Integer, String>>> getList() {
        headTitleMap.keySet().parallelStream().forEach(e -> {
            list.parallelStream().forEach(m -> {
                m.forEach((k,v) -> {
                    if(!Optional.ofNullable(v.get(e)).isPresent()){
                        v.put(e,null);
                    }
                });
            });
        });
        return list;
    }

    public void setList(List<Map<Integer, Map<Integer, String>>> list) {
        this.list = list;
    }

    public Map<Integer, String> getHeadTitleMap() {
        return headTitleMap;
    }

    public void setHeadTitleMap(Map<Integer, String> headTitleMap) {
        this.headTitleMap = headTitleMap;
    }


}
